package com.shuw.com.beingfortextproject.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shuw.com.beingfortextproject.BuildConfig;
import com.shuw.com.beingfortextproject.base.BaseApplication;
import com.shuw.com.beingfortextproject.global.Config;
import com.shuw.com.beingfortextproject.utils.TDevice;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ${cs} on 2018/4/27.
 */

public class Networks {

	private static Networks mNetworks;
	private static Api mApi;
	private Retrofit retrofit;
	private static final int DEFAULT_TIMEOUT = 5;

	// 简单单例模式
	public static Networks getInstance(){
		if (mNetworks == null){
			mNetworks = new Networks();
		}
		return mNetworks;
	}

	public Api getApi(){
		return mApi == null?configRetrofit(Api.class, Config.BaseUrl):mApi;
	}

	private <T>T configRetrofit(Class<T> service, String baseUrl) {
		retrofit = new Retrofit.Builder()
				.baseUrl(baseUrl)
				.client(configClient())
				.addConverterFactory(GsonConverterFactory.create(buildGson()))
				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
				.build();
		return retrofit.create(service);
	}

	private Gson buildGson() {
		return new GsonBuilder()
				.setDateFormat("yyyy-MM-dd HH:mm:ss")
				.registerTypeAdapter(Integer.class,new IntegerDefaultAdapter())
				.registerTypeAdapter(int.class,new IntegerDefaultAdapter())
				.create();
	}

	private OkHttpClient configClient() {
		OkHttpClient.Builder builder = new OkHttpClient.Builder();
		// 设置缓存拦截器
		builder.addNetworkInterceptor(getCacheInterceptor());
		if (BuildConfig.DEBUG){
			HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
			logging.setLevel(HttpLoggingInterceptor.Level.BODY);
			// 设置日志拦截器
			builder.addInterceptor(logging);
		}
		Cache cache = new Cache(BaseApplication.getInstance().getCacheDir(),10*1024*1024);
		// 设置缓存
		builder.cache(cache);
		// 设置请求超时
		builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
		return builder.build();
	}

	private Interceptor getCacheInterceptor() {
		return new Interceptor() {
			@Override
			public Response intercept(Chain chain) throws IOException {
				Request request = chain.request();
				if (!TDevice.hasInternet()){
					request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
				}
				Response response = chain.proceed(request);
				return response;
			}
		};
	}
}
